var frameType = 'print';
function getPoint(obj) { //获取某元素以浏览器左上角为原点的坐标
    var t = obj.offsetTop; //获取该元素对应父容器的上边距
    var l = obj.offsetLeft; //对应父容器的上边距
    //判断是否有父容器，如果存在则累加其边距
    while (obj = obj.offsetParent) {//等效 obj = obj.offsetParent;while (obj != undefined)
        t += obj.offsetTop; //叠加父容器的上边距
        l += obj.offsetLeft; //叠加父容器的左边距
    }
    return {top:t,left:l};
}

function mergeArr(arr1,arr2){
    var arr = [];
    appendArrTo(arr,arr1);
    appendArrTo(arr,arr2);
    return arr;
}

function appendArrTo(arr,tmpArr){
    for( var i=0 ; i<tmpArr.length ; i++ ){
        arr[arr.length] = tmpArr[i];
    }
}

$(function () {

    $(document).keydown(function(event){
        //按下回车键时触发，keyCode为13时，表示回车键
        if(event.keyCode=="46"){
            $('#printCenter label[c="1"][select="1"]').remove();
        }
    });

    var leftWidth = 205,rightWidth=360,topHeight=50,bodyHeight;
    var width = $(document).width();

    $('.print-top').height(topHeight);
    $('.print-left').css({"padding-top":topHeight+"px"}).width(leftWidth);
    $('.print-right').css({"padding-top":topHeight+"px","padding-left":leftWidth+"px"});

    bodyHeight = $(document.body).height();

    $('.print-left .out').width(leftWidth-6).height(bodyHeight-topHeight-6).css({"margin-left":"2px","margin-top":"3px"});
    $('.print-right .out').width(width-leftWidth-6).height(bodyHeight-topHeight-6).css({"margin-left":"2px","margin-top":"3px"});

    $('.print-property').height(bodyHeight-topHeight-6).css({"top":(topHeight+3)+"px"});

    $('#printCenter').css({"margin-left":($('.print-right .out').width()-300-$('#printCenter').width()+10)/2+"px"});

    for(var i=0 ; i<whole.data.length ; i++){
        $('#whole').append('<br/>');
        $('#whole').append(createPrintTable(whole.data[i]));
    }

    for(var i=0 ; i<property.data.length ; i++){
        $('#property').append('<br/>');
        $('#property').append(createPrintTable(property.data[i]));
    }

    for(var i=0 ; i<table.data.length ; i++){
        $('#table').append('<br/>');
        $('#table').append(createPrintTable(table.data[i]));
    }

    $(document.body).click(endEdit);

    $('#view').click(viewPrint);
    $('#save').click(savePrint);

    var heads = ordersData.orders[0].order[0];
    if(ordersData.orders[0].order[1].length>0){
        for( var i=0 ; i<ordersData.orders[0].order[1].length ; i++ ){
            heads = mergeArr(heads,ordersData.orders[0].order[1][i]);
        }
    }
    createLeftLabel(heads,'表头');

    var bodys = ordersData.orders[0].orderDetail[0];
    if(ordersData.orders[0].orderDetail[1].length>0){
        for( var i=0 ; i<ordersData.orders[0].orderDetail[1].length ; i++ ){
            bodys = mergeArr(bodys,ordersData.orders[0].orderDetail[1][i]);
        }
    }
    createLeftLabel(bodys,'表体');

    $('.print-top .icon > label').each(function (i,label) {
        $(label).draggable({
            revert:false,scroll:false,zIndex:10000,addClasses: false,helper: "clone"
        });
    });

    function createLeftLabel(heads,title){
        var leftDiv = $('<fieldset><legend>'+title+'</legend></fieldset>');
        for( var i=0 ; i<heads.length ; i++ ){
            var row = heads[i];
            var moveLabel = $('<label type="bind" data-name="'+row.value+'" class="print-move-span" ><span type="text">'+row.name+'</span></label>');
            moveLabel.data({org:row});
            moveLabel.draggable({
                revert:false,scroll:false,zIndex:10000,addClasses: false,helper: "clone"
            });
            leftDiv.append(moveLabel);
        }
        $('.print-left .out').append(leftDiv);
    }

    // drag drop

    $('#printCenter').data({property:{paperType:'A42',height:148.5,width:210,taoda:0}});

    $( "#printCenter" ).click(function () {
        endEdit();
        $('#property').hide();
        $('#table').hide();
        $('#whole').show();
        $('label[c="1"]').css({"border":"1px solid gray"});
        $('label[c="1"]').attr('select','0');
        $('label[c="1"][type="font"]').css({"border":"none"});
    });

    $( "#printCenter" ).droppable({
        drop: printCenterDrop
    });

    initEdit();
});

function initEdit() {
    var data = {id:params.id,bussType:params.bussType};
    data.loginUserId = params.loginUserId;
    data.customerId = params.customerId;
    data.loginCompanyId = params.loginCompanyId;
    data.loginCompanyLogicalCode = params.loginCompanyLogicalCode;
    if( params.id ){
        app.request({
            url:'print/get',
            data:data,
            success:function (resp) {
                if( resp.result ==0 ){
                    var json = resp.data.json;
                    json = $.parseJSON(json);
                    console.log('json123,',json);
                    initLables(json);
                }else{
                    app.message(layer,'加载数据失败，请重试');
                }

            }
        });
    }
}

function initLables(json) {
    var labels = json.labels;
    for( var i=0 ; i<labels.length ; i++ ){
        initLable(labels[i]);
    }
}

function initLable(data) {
    var property = data.property;
    if( data.type == "table" ){
        var dragEle = $('<label type="'+data.type+'" data-name="account.name" class="print-move-span"><i class="fa fa-table"></i></label>');
        dragEle.attr("style",data.style);
        delete property.type;
        printCenterDropCommon(property.x,property.y,dragEle,property);
    }else{
        var dragEle = $('<label type="'+data.type+'" data-name="account.name" class="print-move-span"><span type="text">结算账户</span></label>');
        delete property.type;
        printCenterDropCommon(property.x,property.y,dragEle,property);
    }

}

function printCenterDrop(event, ui) {
    var dragEle = ui.draggable;
    if( dragEle.attr('c') == 1 ){
        return;
    }
    var point = getPoint(this);
    var x = event.pageX-point.left;
    var y = event.pageY-point.top;
    printCenterDropCommon(x,y,dragEle);

}

function printCenterDropCommon(x,y,dragEle,property) {
    var dragEleType = dragEle.attr('type');
    var defProperty = {};
    if( property ){
        defProperty = property;
    }else{
        if( dragEleType == 'table' ){
            $.extend(defProperty,defaultTable);
        }else{
            $.extend(defProperty,defaultProperty);
        }
    }

    var propertyTargetId = dragEleType == 'table'?'#table':'#property';

    var dragEleClone = dragEle.clone();
    dragEleClone.data({org:dragEle.data().org});
    var tid = 't'+new Date().getTime();
    dragEleClone.attr('c','1').attr('select','0').attr('id',tid).css({
        "cursor":"pointer","position":"absolute","top":y+"px","left":x+"px","margin-top":"0px","margin-left":"0px","box-shadow":"none","z-index":"1",
        "border":"1px solid gray","padding-left":"0px",
        "font-family":defProperty.font[0] ,"font-weight": defProperty.font[1],"font-style": defProperty.font[2],
        "font-size": defProperty.font[3]+"px","text-decoration":defProperty.font[4],
    }).draggable({
        containment:'#printCenter',
        stop: function( event, ui ) {
            var target = event.target;
            var id = $(target)[0].id;
            setPropertys(id,{x:getCss($(target),'left'),y:getCss($(target),'top')});
        }
    });
    if( dragEleType != 'table' ){
        var txt_name = dragEleClone.text();
        defProperty.data = txt_name;
        if(txt_name)defProperty.txt_name = txt_name;
    }

    dragEleClone.data({property:defProperty});

    dragEleClone.click(function (event) {
        dragEleClick($(this),event);
    });



    printCenterFontDrop(dragEle,dragEleClone);

    dragEleClone.resizable({
        stop: function( event, ui ) {
            var target = event.target;
            var id = $(target)[0].id;
            setPropertys(id,{width:getCss($(target),'width'),height:getCss($(target),'height')});
        }
    });

    $('#printCenter').append(dragEleClone);
    if(!property){
        defProperty.x = x;
        defProperty.y = y;
        defProperty.width = getCss(dragEleClone,'width');
        defProperty.height = getCss(dragEleClone,'height');
        setPropertys(tid,defProperty,propertyTargetId);
    }
}

function printCenterFontDrop(dragEle,dragEleClone) {
    var dragEleType = dragEle.attr('type');
    if(  dragEleType == 'font'  ){
        dragEleClone.width(54).height(18).css({"border":"none"});
        dragEleClone.html('<span type="text">显示文本</span>');
    }else if(  dragEleType == 'table'  ){
        dragEleClone.width(666).height(230);
    }
}

function getCss(ele,name) {
   return ele.css(name).replace('px','');
}

function dragEleClick(_this,event) {
    endEdit();
    $('label[c="1"]').attr('select',"0").css({"border":"1px solid gray"});
    $('label[c="1"][type="font"]').css({"border":"none"});
    _this.attr('select','1').css({"border":"1px solid #69C1F2"});

    var type = _this.attr('type');
    if( type == 'table' ){
        $('#property').hide();
        $('#whole').hide();
        $('#table').show();
    }else{
        initPropertys(_this.data().property);
        $('#property').show();
        $('#whole').hide();
        $('#table').hide();
    }

    event.stopPropagation();
}

function initPropertys(property) {
    for (var n in property){
        initProperty(n,property[n]);
    }
}

function viewPrint() {
    window.open(app.getBaseUrl()+"html/system/print/print_view.html", "_blank");
}

var params = app.getRequestParams();
function savePrint() {
    var wholeData = {labels:[],whole:$('#printCenter').data().property};
    $('label[c="1"]').each(function () {
        var _this = $(this);
        var _thisData = _this.data();
        var style = _this.attr('style');
        var label = {style:style,className:'print-move-span',name:_thisData.name,property:_thisData.property};
        label.type = _this.attr('type');
        wholeData.labels.push(label);
    });
    var data = {json:JSON.stringify(wholeData),bussType:params.bussType};
    data.loginUserId = params.loginUserId;
    data.customerId = params.customerId;
    data.loginCompanyId = params.loginCompanyId;
    data.loginCompanyLogicalCode = params.loginCompanyLogicalCode;
    var url = 'print/insert';
    if( params.id ){
        url = 'print/update';
        data.id = params.id;
    }
    console.log("789456---,,,",JSON.stringify(data));
    //
    app.request({
        url:url,
        data:data,
        success:function (resp) {
            if( resp.result==0 ){
                app.message(layer,'操作成功');
            }else{
                app.message(layer,'操作失败【'+app.getErrorMsg(resp)+'】',2);
            }
        }
    });
}

function getTargetWindow() {
    var priframes = top.frames;
    for( var i=0 ; i<priframes.length ; i++ ){
        if(priframes[i].frameType=='table'){
            return priframes[i];
        }
    }
    return parent;
}